package com.mall.shopping.services;

import com.mall.shopping.IHomeService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.ContentConverter;
import com.mall.shopping.dal.entitys.Panel;
import com.mall.shopping.dal.entitys.PanelContentItem;
import com.mall.shopping.dal.persistence.PanelContentMapper;
import com.mall.shopping.dal.persistence.PanelMapper;
import com.mall.shopping.dto.HomePageResponse;
import com.mall.shopping.dto.PanelContentItemDto;
import com.mall.shopping.dto.PanelDto;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author wangdezhao
 * @date 2021/6/17
 * @description
 */
@Service // 要引用dubbo的!
public class IHomeServiceImpl implements IHomeService {
    @Autowired
    PanelContentMapper panelContentMapper;

    @Autowired
    PanelMapper panelMapper;

    @Autowired
    ContentConverter contentConverter;

    /**
     * 一共30多个 可以直接一次一次查
     * @return
     */
    @Override
    public HomePageResponse homepage() {

        HomePageResponse homePageResponse = new HomePageResponse(); // 返回的response对象

        try {

            Set<PanelDto> panelDtoSet = new HashSet<>(); // response对象的成员变量

            List<Panel> panels = panelMapper.selectAll(); // 全部取出panels

            for (Panel panel : panels) { // 连接item表,去查询 contentItems

                PanelDto panelDto = contentConverter.panel2Dto(panel); // panel 转 DTO
                List<PanelContentItem> panelContentItems = panelContentMapper.selectPanelContentAndProductWithPanelId(panel.getId());
                List<PanelContentItemDto> panelContentItemDtos = contentConverter.panelContentItem2Dto(panelContentItems); //  转 DTO
                panelDto.setPanelContentItems(panelContentItemDtos); // panelDto 赋值
                panelDtoSet.add(panelDto);

            }
            // response对象成功,返回对象
            homePageResponse.setPanelContentItemDtos(panelDtoSet);
            homePageResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            homePageResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (Exception e) {  // 发生异常直接返回失败

            homePageResponse.setMsg(ShoppingRetCode.SYSTEM_ERROR.getMessage());
            homePageResponse.setCode(ShoppingRetCode.SYSTEM_ERROR.getCode());

        }
        return homePageResponse;
    }
}
